package com.lz.ovuola.util.redis.cluster;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import com.lz.ovuola.util.exception.AppStartupException;

/**
 * Jedis does not support password protected Redis Cluster configurations!
 * 
 * @author fz
 *
 */
@Configuration
public class JedisClusterConfig {

	@Autowired
	private RedisProperties redisProperties;

	@Autowired
	private JedisPoolConfig jedisPoolConfig;

	@Bean
	public JedisCluster getJedisCluster() {

		String[] serverArray = redisProperties.getClusterNodes().split(",");
		Set<HostAndPort> nodes = new HashSet<HostAndPort>(serverArray.length);
		for (String ipPort : serverArray) {
			String[] ipPortPair = ipPort.split(":");
			if (ipPortPair.length != 2) {
				throw new AppStartupException(
						"ip or Port is required,but is null");
			}
			nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer
					.valueOf(ipPortPair[1].trim())));
		}
		return new JedisCluster(nodes, redisProperties.getCommandTimeout(),
				jedisPoolConfig);
	}

}
